package com.aquarium.ui.controller;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.RadioButton;

import com.aquarium.R;
import com.aquarium.config.ModuleData;
import com.aquarium.config.WaterMotorData;
import com.aquarium.data.ModuleSettingDataBase;
import com.aquarium.module.ModuleControlService;

public class WaterMotorTimePicker extends ModuleTimePicker {

	private final static String TAG = "WaterMotorTimePicker";

	private RadioButton mWaterMotorOpenRadioBtn;
	private RadioButton mWaterMotorCloseRadioBtn;

	private int mPosition;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.water_motor_time_picker);
		init();
	}

	@Override
	public void init() {
		super.init();
		if (mIntentAction.equals(ControllerSetting.ACTION_MODIFY_SETTING)) {
			mPosition = getIntent().getIntExtra(
					ControllerSetting.INTENT_EXTRA_LISTVIEW_CLICKED_POSITION, -1);
			if (mPosition != -1) {
				WaterMotorData data = mModuleSettingDataBase
						.queryWaterMotorData(mModuleSettingDataBase.getCursor(
								ModuleSettingDataBase.WATER_MOTOR_TABLE,
								mPosition));
				setWidgetValue(data);
			}
		}
	}

	@Override
	public void setWidgetValue(ModuleData data) {
		super.setWidgetValue(data);
		if (((WaterMotorData) data).isOn) {
			mWaterMotorOpenRadioBtn.setChecked(true);
			mWaterMotorCloseRadioBtn.setChecked(false);
		} else {
			mWaterMotorOpenRadioBtn.setChecked(false);
			mWaterMotorCloseRadioBtn.setChecked(true);
		}
	}

	@Override
	public void findViews() {
		super.findViews();
		mWaterMotorOpenRadioBtn = (RadioButton) findViewById(R.id.water_motor_open);
		mWaterMotorCloseRadioBtn = (RadioButton) findViewById(R.id.water_motor_close);
	}

	@Override
	public void setListeners() {
		super.setListeners();
		mOkButton.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				WaterMotorData data = new WaterMotorData();
				setModuleData(data);
				data.isOn = mWaterMotorOpenRadioBtn.isChecked() ? true : false;
				if (mIntentAction.equals(ControllerSetting.ACTION_ADD_SETTING)) {
					mModuleSettingDataBase.insertWaterMotorData(data);
				} else if (mIntentAction
						.equals(ControllerSetting.ACTION_MODIFY_SETTING)) {
					mModuleSettingDataBase
							.updateWaterMotorData(mPosition, data);
				}
				Intent intent = new Intent();
				intent.setAction(ModuleControlService.ACTION_UPDATE_WATER_MOTOR_DATA);
				sendBroadcast(intent);
				finish();
			}
		});
		mCancelButton.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				finish();

			}
		});
	}
}
